package com.zhumo.sz.common.utils;

import com.zhumo.sz.common.config.ProjectCommonConfig;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;

/**
 * @author zhumo
 * @comment 配置文件工具类 封装各种配置文件加载相关操作
 */

@Slf4j
public class PropertiesUtil {

    /**
     * 读取配置文件
     * @param path 路径
     */
    public static Properties loadProperties(String path) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(new File(path)));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("配置文件 {} 读取出现异常",path);
        }
        return properties;
    }

    /**
     * 手写将项目配置中的所有配置项及其值转换为map形式, Properties的底层 load()是基于HashTable实现的,
     * @param paths 配置路径
     * @return 结果Map
     */
    public static HashMap<String,String> loadAllConfigs(String paths){
        Properties properties = loadProperties(paths);
        ProjectCommonConfig projectCommonConfig = new ProjectCommonConfig();
        Field[] declaredFields = projectCommonConfig.getClass().getDeclaredFields();
        HashMap<String, String> result = new HashMap<>();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String value = null;
            try {
                value = declaredField.get(projectCommonConfig).toString();
                result.put(value,properties.getProperty(value));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if (result.size() != declaredFields.length){
            throw new RuntimeException(String.format("配置文件{}装载异常",paths));
        }
        return result;
    }
}
